package org.example.Agricultural_33.controller;

import org.example.Agricultural_33.model.CommonResponse;
import org.example.Agricultural_33.model.ProductDTO;
import org.example.Agricultural_33.model.bo.AgriculturalTraceabilityGetProductInputBO;
import org.example.Agricultural_33.service.AgriculturalTraceabilityService;
import org.fisco.bcos.sdk.transaction.model.dto.CallResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 数据统计控制器
 */
@RestController
@RequestMapping("/api/statistics")
public class StatisticsController {

    @Autowired
    private AgriculturalTraceabilityService agriculturalTraceabilityService;

    /**
     * 获取产品分布统计
     * @return 产品分布数据
     */
    @GetMapping("/product-distribution")
    public CommonResponse getProductDistribution() {
        try {
            CallResponse response = agriculturalTraceabilityService.getAllProductIds();
            if (response.getReturnObject() instanceof List<?>) {
                @SuppressWarnings("unchecked")
                List<Object> rawProductIds = (List<Object>) response.getReturnObject();
                List<String> productIds = new ArrayList<>();
                
                // 安全转换为String列表
                for (Object obj : rawProductIds) {
                    if (obj instanceof String) {
                        productIds.add((String) obj);
                    }
                }
                
                // 统计不同产地的产品数量
                Map<String, Integer> originCount = new HashMap<>();
                
                for (String id : productIds) {
                    AgriculturalTraceabilityGetProductInputBO inputBO = new AgriculturalTraceabilityGetProductInputBO();
                    inputBO.set_id(id);
                    
                    CallResponse productResponse = agriculturalTraceabilityService.getProduct(inputBO);
                    if (productResponse.getReturnObject() instanceof List) {
                        List<Object> productInfo = (List<Object>) productResponse.getReturnObject();
                        if (productInfo.size() >= 5) {
                            String origin = productInfo.get(4).toString();
                            
                            // 检查是否已删除
                            Boolean isDeleted = productInfo.size() > 7 ? 
                                    (productInfo.get(7) instanceof Boolean ? (Boolean) productInfo.get(7) : false) : 
                                    false;
                            if (!isDeleted) {
                                originCount.put(origin, originCount.getOrDefault(origin, 0) + 1);
                            }
                        }
                    }
                }
                
                return CommonResponse.ok(originCount);
            }
            return CommonResponse.ok(Collections.emptyMap());
        } catch (Exception e) {
            return CommonResponse.fail("ST001", e);
        }
    }

    /**
     * 获取最近创建的产品
     * @return 最近创建的产品列表
     */
    @GetMapping("/recent-products")
    public CommonResponse getRecentProducts() {
        try {
            CallResponse response = agriculturalTraceabilityService.getAllProductIds();
            if (response.getReturnObject() instanceof List<?>) {
                @SuppressWarnings("unchecked")
                List<Object> rawProductIds = (List<Object>) response.getReturnObject();
                List<String> productIds = new ArrayList<>();
                
                // 安全转换为String列表
                for (Object obj : rawProductIds) {
                    if (obj instanceof String) {
                        productIds.add((String) obj);
                    }
                }
                
                List<ProductDTO> products = new ArrayList<>();
                
                for (String id : productIds) {
                    AgriculturalTraceabilityGetProductInputBO inputBO = new AgriculturalTraceabilityGetProductInputBO();
                    inputBO.set_id(id);
                    
                    CallResponse productResponse = agriculturalTraceabilityService.getProduct(inputBO);
                    if (productResponse.getReturnObject() instanceof List) {
                        List<Object> productInfo = (List<Object>) productResponse.getReturnObject();
                        if (productInfo.size() >= 8) {
                            ProductDTO productDTO = new ProductDTO();
                            productDTO.setId(id);
                            productDTO.setName(productInfo.get(0).toString());
                            productDTO.setProducer(productInfo.get(1).toString());
                            productDTO.setOrigin(productInfo.get(2).toString());
                            
                            // 安全处理BigInteger类型
                            if (productInfo.get(3) instanceof BigInteger) {
                                productDTO.setProductionDate((BigInteger) productInfo.get(3));
                            } else if (productInfo.get(3) instanceof Number) {
                                productDTO.setProductionDate(BigInteger.valueOf(((Number) productInfo.get(3)).longValue()));
                            } else {
                                productDTO.setProductionDate(BigInteger.ZERO);
                            }
                            
                            // 处理检验记录列表
                            if (productInfo.get(4) instanceof List) {
                                @SuppressWarnings("unchecked")
                                List<Object> rawInspections = (List<Object>) productInfo.get(4);
                                List<String> inspections = new ArrayList<>();
                                
                                for (Object inspection : rawInspections) {
                                    inspections.add(inspection.toString());
                                }
                                
                                productDTO.setInspections(inspections);
                            } else {
                                productDTO.setInspections(new ArrayList<>());
                            }
                            
                            productDTO.setOwner(productInfo.get(5).toString());
                            
                            // 安全处理布尔类型
                            if (productInfo.get(6) instanceof Boolean) {
                                productDTO.setIsDeleted((Boolean) productInfo.get(6));
                            } else {
                                productDTO.setIsDeleted(false);
                            }
                            
                            if (!productDTO.getIsDeleted()) {
                                products.add(productDTO);
                            }
                        }
                    }
                }
                
                // 按生产日期排序，最新的在前面
                products.sort((p1, p2) -> p2.getProductionDate().compareTo(p1.getProductionDate()));
                
                // 返回前10个产品
                int limit = Math.min(10, products.size());
                return CommonResponse.ok(products.subList(0, limit));
            }
            return CommonResponse.ok(Collections.emptyList());
        } catch (Exception e) {
            return CommonResponse.fail("ST002", e);
        }
    }

    /**
     * 获取各生产者的产品数量
     * @return 生产者统计数据
     */
    @GetMapping("/producer-statistics")
    public CommonResponse getProducerStatistics() {
        try {
            CallResponse response = agriculturalTraceabilityService.getAllProductIds();
            if (response.getReturnObject() instanceof List<?>) {
                @SuppressWarnings("unchecked")
                List<Object> rawProductIds = (List<Object>) response.getReturnObject();
                List<String> productIds = new ArrayList<>();
                
                // 安全转换为String列表
                for (Object obj : rawProductIds) {
                    if (obj instanceof String) {
                        productIds.add((String) obj);
                    }
                }
                
                // 统计不同生产者的产品数量
                Map<String, Integer> producerCount = new HashMap<>();
                
                for (String id : productIds) {
                    AgriculturalTraceabilityGetProductInputBO inputBO = new AgriculturalTraceabilityGetProductInputBO();
                    inputBO.set_id(id);
                    
                    CallResponse productResponse = agriculturalTraceabilityService.getProduct(inputBO);
                    if (productResponse.getReturnObject() instanceof List) {
                        List<Object> productInfo = (List<Object>) productResponse.getReturnObject();
                        if (productInfo.size() >= 8) {
                            String producer = productInfo.get(1).toString();
                            
                            // 安全处理布尔类型
                            Boolean isDeleted = false;
                            if (productInfo.get(6) instanceof Boolean) {
                                isDeleted = (Boolean) productInfo.get(6);
                            }
                            
                            if (!isDeleted) {
                                producerCount.put(producer, producerCount.getOrDefault(producer, 0) + 1);
                            }
                        }
                    }
                }
                
                // 转换为排序后的列表
                List<Map<String, Object>> result = producerCount.entrySet().stream()
                        .sorted((e1, e2) -> e2.getValue().compareTo(e1.getValue()))
                        .map(entry -> {
                            Map<String, Object> item = new HashMap<>();
                            item.put("producer", entry.getKey());
                            item.put("count", entry.getValue());
                            return item;
                        })
                        .collect(Collectors.toList());
                
                return CommonResponse.ok(result);
            }
            return CommonResponse.ok(Collections.emptyList());
        } catch (Exception e) {
            return CommonResponse.fail("ST003", e);
        }
    }
} 